/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */
package com.ykht.proj.coupon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ykht.proj.common.core.exception.BusinessException;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.ConfBrandPersonEnum;
import com.ykht.proj.coupon.Enum.DelFlagEnum;
import com.ykht.proj.coupon.Enum.MerchantTypeEnum;
import com.ykht.proj.coupon.entity.*;
import com.ykht.proj.coupon.mapper.FxConfBrandPersonMapper;
import com.ykht.proj.coupon.mapper.FxMerchantAccountMapper;
import com.ykht.proj.coupon.service.*;
import com.ykht.proj.coupon.vo.FxConfBrandPersonVo;
import com.ykht.proj.coupon.vo.FxMerchantAccountVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 品牌对c端的分销表
 *
 * @author proj code generator
 * @date 2021-08-12 14:10:38
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy, @Autowired})
public class FxConfBrandPersonServiceImpl extends ServiceImpl<FxConfBrandPersonMapper, FxConfBrandPerson> implements FxConfBrandPersonService {

	private final FxConfBrandPersonMapper fxConfBrandPersonMapper;
	private final CnCouponLogService cnCouponLogService;
	private final FxRewardPersonService fxRewardPersonService;
	private final FxMerchantAccountService fxMerchantAccountService;
	private final FxShareService fxShareService;
	private final FxMerchantAccountMapper fxMerchantAccountMapper;


	/**
	 * 分页查询 品牌对c端的分销表
	 *
	 * @param page                分页对象
	 * @param fxConfBrandPersonVo 品牌对c端的分销表
	 * @return
	 */
	@Override
	public IPage<FxConfBrandPersonVo> getFxConfBrandPersonPage(Page page, FxConfBrandPersonVo fxConfBrandPersonVo) {
		return fxConfBrandPersonMapper.getFxConfBrandPersonPage(page, fxConfBrandPersonVo);
	}

	/**
	 * 通过id查询品牌对c端的分销表
	 *
	 * @param id
	 * @return
	 */
	@Override
	public FxConfBrandPersonVo getByIdFxConfBrandPerson(Long id) {
		FxConfBrandPersonVo brandPersonVo = BeanUtil.toBean(this.getById(id), FxConfBrandPersonVo.class);
		// 获取账号可用余额
//		FxMerchantAccountVo fxMerchantAccountVo =  new FxMerchantAccountVo();
//		fxMerchantAccountVo.setTatId(brandPersonVo.getBrandId());
//		fxMerchantAccountVo.setType(2);
//		fxMerchantAccountVo = fxMerchantAccountService.getByIdAccountDetails(fxMerchantAccountVo);
//		brandPersonVo.setAccountBalance(fxMerchantAccountVo.getBalance());
		 // 核销人数
		int verificationCount = cnCouponLogService.count(Wrappers.lambdaQuery(CnCouponLog.class)
				.eq(CnCouponLog::getConfBrandPersonId, id)
				.eq(CnCouponLog::getStatus, 1)
				.isNotNull(CnCouponLog::getShareId)
				.groupBy(CnCouponLog::getRecipientId));
		brandPersonVo.setVerificationCount(verificationCount);
		// 分销领券人数
		int receiveCouponCount = cnCouponLogService.count(Wrappers.lambdaQuery(CnCouponLog.class)
				.eq(CnCouponLog::getConfBrandPersonId, id)
				.isNotNull(CnCouponLog::getShareId)
				.groupBy(CnCouponLog::getRecipientId));
		brandPersonVo.setReceiveCouponCount(receiveCouponCount);
		// 返佣数
		int returnMoneyCount = fxRewardPersonService.count(Wrappers.lambdaQuery(FxRewardPerson.class)
				.eq(FxRewardPerson::getBrandId, brandPersonVo.getBrandId())
				.eq(FxRewardPerson::getStatus, 1));
		brandPersonVo.setReturnMoneyCount(returnMoneyCount);
		// 分享次数
		int shareCount = fxShareService.count(Wrappers.lambdaQuery(FxShare.class)
				.eq(FxShare::getConfBrandPersonId,id));
		brandPersonVo.setShareCount(shareCount);
		return brandPersonVo;
	}

//	@Override
//	@Transactional(rollbackFor = Exception.class)
//	public FxConfBrandPerson addOrUpdateConfBrandPerson(FxConfBrandPerson fxConfBrandPerson) {
//		FxConfBrandPerson brandPerson = this.getOne(Wrappers.lambdaQuery(FxConfBrandPerson.class)
//				.eq(FxConfBrandPerson::getBrandId, SecurityUtils.getSjId()));
//		if (null == brandPerson){
//			brandPerson = fxConfBrandPerson;
//			brandPerson.setBrandId(SecurityUtils.getSjId());
//			brandPerson.setCreateTime(LocalDateTime.now());
//			brandPerson.setCreateUser(SecurityUtils.getUserId());
//			brandPerson.setVerificationCouponCount(0);
//			brandPerson.setSurplusPushNum(fxConfBrandPerson.getPushNum());
//			brandPerson.setReconfTime(LocalDateTime.now());
//			this.save(brandPerson);
//			fxMerchantAccountService.updateMerchantAccount(MerchantTypeEnum.brand.getValue(), brandPerson.getBrandId(), brandPerson.getPushMoney().negate(),
//					null, brandPerson.getPushMoney(), null,
//					null, null, SecurityUtils.getUserId());
//		} else {
//			//根据冻结金额更新余额
//			fxMerchantAccountMapper.updateMerchantAccount4ConfFx(MerchantTypeEnum.brand.getValue(), brandPerson.getBrandId(),fxConfBrandPerson.getPushMoney(), SecurityUtils.getUserId());
//			fxConfBrandPerson.setId(brandPerson.getId());
//			fxConfBrandPerson.setUpdateTime(LocalDateTime.now());
//			fxConfBrandPerson.setUpdateUser(SecurityUtils.getUserId());
//			fxConfBrandPerson.setSurplusPushNum(fxConfBrandPerson.getPushNum());
//			fxConfBrandPerson.setVerificationCouponCount(0);//测试说每次跟新就要清理为0， 9-13日
//			brandPerson.setReconfTime(LocalDateTime.now());
//			this.updateById(fxConfBrandPerson);
//			brandPerson = fxConfBrandPerson;
//		}
//		return brandPerson;
//	}

	@Override
	public FxConfBrandPerson create(FxConfBrandPerson brandPerson) {
		//校验时间
		this.checkTime(brandPerson);
		brandPerson.setBrandId(SecurityUtils.getSjId());
		brandPerson.setCreateTime(LocalDateTime.now());
		brandPerson.setCreateUser(SecurityUtils.getUserId());
		brandPerson.setVerificationCouponCount(0);
		brandPerson.setSurplusPushNum(brandPerson.getPushNum());
		brandPerson.setReconfTime(LocalDateTime.now());
		this.save(brandPerson);
		fxMerchantAccountService.updateMerchantAccount(MerchantTypeEnum.brand.getValue(), brandPerson.getBrandId(), brandPerson.getPushMoney().negate(),
				null, brandPerson.getPushMoney(), null, null, null, SecurityUtils.getUserId());
		return brandPerson;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public FxConfBrandPerson updateObj(FxConfBrandPerson fxConfBrandPerson) {
		this.checkTime(fxConfBrandPerson);
		//获取最初的配置
		FxConfBrandPerson old = this.getById(fxConfBrandPerson.getId());
		//和当前更新的配置进行比较
		BigDecimal money = fxConfBrandPerson.getPushMoney().subtract(old.getPushMoney());
		//根据冻结金额更新余额
		fxMerchantAccountMapper.updateMerchantAccount(MerchantTypeEnum.brand.getValue(), fxConfBrandPerson.getBrandId(),money,money,money.negate()
				,null,null,null, SecurityUtils.getUserId());
		fxConfBrandPerson.setUpdateTime(LocalDateTime.now());
		fxConfBrandPerson.setUpdateUser(SecurityUtils.getUserId());
		fxConfBrandPerson.setSurplusPushNum(fxConfBrandPerson.getPushNum());
		fxConfBrandPerson.setVerificationCouponCount(0);//测试说每次跟新就要清理为0， 9-13日
		fxConfBrandPerson.setReconfTime(LocalDateTime.now());
		this.updateById(fxConfBrandPerson);
		return fxConfBrandPerson;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public FxConfBrandPerson finish(Long id) {
		FxConfBrandPerson confBrandPerson = this.getById(id);
		//更新状态为结束
		confBrandPerson.setSwitchs(ConfBrandPersonEnum.FINISHED.getValue());
		confBrandPerson.setSurplusPushNum(0);
		confBrandPerson.updateById();
		BigDecimal money = confBrandPerson.getReturnMoney().multiply(BigDecimal.valueOf(confBrandPerson.getSurplusPushNum()));
		//结算账户金额
		fxMerchantAccountMapper.updateMerchantAccount(MerchantTypeEnum.brand.getValue(), confBrandPerson.getBrandId(),money,money,money.negate()
				,null,null,null, SecurityUtils.getUserId());
		return confBrandPerson;
	}

	private void checkTime(FxConfBrandPerson brandPerson) {
		if (1==1){
			throw new BusinessException("活动时间段有交叉");
		}
	}


	@Override
	public FxConfBrandPerson findEnableConf(Long brandId) {
		FxConfBrandPerson fxConfBrandPerson = null;
		if (brandId!=null){
			 fxConfBrandPerson = this.getOne(Wrappers.lambdaQuery(FxConfBrandPerson.class).eq(FxConfBrandPerson::getBrandId,brandId).eq(FxConfBrandPerson::getSwitchs,0));
			return fxConfBrandPerson;
		}
		return fxConfBrandPerson;
	}


	@Override
	public Integer fxFlag(Long brandId) {
		//0不参与1参与
		int flag = 0;
		//全局开启
		Integer fxcount = new FxConfRewardBaseGlobel().selectCount(Wrappers.lambdaQuery(FxConfRewardBaseGlobel.class).eq(FxConfRewardBaseGlobel::getFxFlagDisplay, 0));
		if (fxcount>0){
			//品牌开启
			Integer count = this.count(Wrappers.lambdaQuery(FxConfBrandPerson.class).eq(FxConfBrandPerson::getBrandId,brandId).eq(FxConfBrandPerson::getSwitchs,0));
			flag = count>0?1:0;
		}
		return flag;
	}

}
